﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractPcon;
using HamcoWcs.Contract.ContractSrm;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.NodeInfos;
using HamcoWcs.Entitys.SubTasks;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.Devices;
using HamcoWcs.Models.NodeInfos;
using HamcoWcs.Service.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace HamcoWcs.Service.Srm.SrmTaskFinders
{
    /// <summary>
    /// 堆垛机查找任务策略<br/>
    /// 优先级>时间
    /// </summary>
    public class SrmTaskFinder_Sequence : SrmTaskFinderBase
    {
        public override SubTask Find(SrmDto srm)
        {
            var isCanDo = srm.IsCanDo();
            if (!isCanDo) return null;

            // 特殊情况，判断堆垛机是否有有货无任务，找到已下发的任务并重发
            if (srm.IsGoods == 1)
                return GetMissingTask(srm);
            // 特殊情况，判断堆垛机是否无任务，但WCS有对应的任务
            var onProgressTask = GetOnProgressTask(srm);
            //if (onProgressTask != null && true) return onProgressTask;
            if (onProgressTask != null)
            {
                if (IsTaskCanDo(onProgressTask))
                {
                    return onProgressTask;
                }
                else
                {
                    return null;
                }
            }

            // 获取该堆垛机的优先级最高的任务
            var mainTask = _wcsDbContext.MainTasks
                .OrderByDescending(x => x.Priority)
                .ThenByDescending(x => x.CreatedTime)
                .Include(x => x.SubTasks)
                .Where(x => x.SubTasks.Any(s => s.PlcName == srm.SrmName
                                             && s.TaskStatus == EnumSubTaskStatus.Ready.ToString()))
                .FirstOrDefault();

            if (mainTask is null) return null;


            var subtask = mainTask.SubTasks.FirstOrDefault(x => x.TaskStatus == EnumSubTaskStatus.Ready.ToString());

            if (IsTaskCanDo(subtask))
            {
                if (mainTask.TaskStatus == EnumMainTaskStatus.Ready.ToString())
                {
                    mainTask.TaskStatus = EnumMainTaskStatus.OnProgress.ToString();
                    _wcsDbContext.SaveChanges();
                }
                return subtask;
            }

            return null;
        }


        // 不判断干涉
        protected override bool CheckInterfere(SubTask task) => false;


        public SrmTaskFinder_Sequence(AutomaticStorageInfo asrs, WcsDbContext wcsDbContext, IBaseConfigService config, IMapper mapper, IPathService pathService, IPconBaseService pconBaseService, IBaseSrmTaskService srmTaskService, ILocationService locationService)
    : base(wcsDbContext, mapper, config, pathService, pconBaseService, srmTaskService, locationService, asrs)
        {
        }

        public override string Policy => "Sequence";
    }
}
